<template>
    <div class="d-flex page-content">
        <div class="onChain-page">
            <div class="top">
                <jLink :list="breadcrumbs" @hit="backTo"></jLink>
            </div>
            <div class="content">
                <p class="content-title">{{ $t('message.Home.d') }}</p>
                <div class="content-Loding" v-if="windowList.length == 0">
                    <v-progress-circular :width="3" :size="40" color="#fcc235" indeterminate></v-progress-circular>
                </div>
                <div v-else>
                    <div class="card-item" v-for="item in windowList">
                        <div class="row1">
                            <div class="d-flex align-center ">
                                <span class="iconfont icon-box"
                                    :class="item.origin?.fromAddressType == 'eoa' ? 'icon-touxiang' : 'icon-icon_xinfang'"></span>
                                <div class="hover-text"
                                    @click="naviGetTo(item.origin, item.origin?.toAddress || item.origin?.toTag)"
                                    v-if="item.origin?.fromAddressType == 'cex'">
                                    {{ item.origin?.toAddress || item.origin?.toTag }}</div>
                                <div class="hover-text" @click="naviGetTo(item.origin, item.address)" v-else>{{
                                    item.address }}
                                </div>
                            </div>
                            <ShareNetwork class="d-inline-flex" @open="reload" :title="item.description"
                                :network="item.network" :hashtags="item.hashtags" description="ChainingView"
                                :link="item.shareURl" :url="item.shareURl">
                                <div class="flook">
                                    <img src="@/assets/fenxiang.png" class="carm">
                                </div>
                            </ShareNetwork>
                        </div>
                        <div class="row2 d-flex justify-space-between align-center">
                            <div class="a-txt" v-if="item.origin?.type == 'swap'">
                                Swap {{ item.origin?.outSymbol }} to {{ item.origin?.inSymbol }}
                            </div>
                            <div class="a-txt" v-else-if="item.origin?.action == 'transfer'">
                                Send to {{ item.origin?.toAddress }} {{ item.origin?.toTag }}
                            </div>
                            <div class="a-txt" v-else-if="item.origin?.action == 'deposit'">
                                {{ item.origin?.action }} to {{ item.origin?.toAddress }} {{ item.origin?.toTag }}
                            </div>
                            <div class="a-txt" v-else>
                                {{ item.origin?.action }} from {{ item.origin?.fromAddress || item.origin?.fromTag }}
                            </div>
                            <span class="row-time">{{ item.time }}</span>
                        </div>
                        <div class="row3" v-if="item.origin?.type == 'swap'">
                            <div class="row3-left d-flex align-center">
                                <img :src="item.outimg" class="i-cons">
                                <span class="amout  outAmout">{{
                                    numberWithCommas(item.origin?.outAmount) }}</span>
                                <span class="symbol hover-text" @click="toToekn(item.origin?.outTokenAddress)">#{{
                                    item.origin?.outSymbol }}</span>
                            </div>
                            <div class="d-flex align-center justify-space-between mt10">
                                <div class="row3-left d-flex align-center">
                                    <img :src="item.inimg" class="i-cons">
                                    <span class="amout inAmout">+{{
                                        numberWithCommas(Math.abs(item.origin?.inAmount)) }}</span>
                                    <span class="symbol hover-text" @click="toToekn(item.origin?.inTokenAddress)">#{{
                                        item.origin?.inSymbol }}</span>
                                </div>
                                <div class="row3-right">{{ numberWithCommas(item.origin?.inusdt ||
                                    item.origin?.outusdt) }}</div>
                            </div>
                        </div>
                        <div class="row3 d-flex align-center justify-space-between" v-else>
                            <div class="row3-left d-flex align-center">
                                <img :src="item.outimg" class="i-cons">
                                <span class="amout amout-def">{{
                                    numberWithCommas(Math.abs(item.origin?.outAmount)) }}</span>
                                <span class="symbol hover-text" @click="toToekn(item.origin?.outTokenAddress)">#{{
                                    item.origin?.outSymbol }}</span>
                            </div>
                            <div class="row3-right">${{ numberWithCommas(item.origin?.inusdt ||
                                item.origin?.outusdt) }}</div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
        <div class="symbol-rank">
            <ranks></ranks>
        </div>
    </div>
</template>

<script setup lang="ts">
import { Bus, CONN_FLUCTUATION, CONN_BIG_AMOUNT, KLINE_RESET } from "@/connetion/Bus";
import { ref, onMounted, onUnmounted, computed, watch } from "vue";
import { formatBigNumber, formatTimeAgo, numberWithCommas } from "@/comm/format";
import { useActivity } from "@/stores/activity";
import { uuidCreate } from "@/comm/uuid";
import { useTokens } from '@/stores/tokens';
import JLoding from "@/components/j-loding/index.vue";
import jLink from "@/components/j-link/index.vue";
import { URL_KLINE_HISTORY, URL_USER_INFO } from "@/comm/api";
import { reload } from "@/comm/tools";
import { get } from "@/comm/request";
import { useRouter } from "vue-router";
import { useUser } from "@/stores/user";
import ranks from '@/views/smartMoney/components/ranks.vue'
import { Platform, ShareItem, shareTags } from "@/comm/ShareConfig"
import Jtwitter from "@/assets/svg/twitter.svg";
import i18n from "@/locals";
import { text } from "stream/consumers";

const breadcrumbs = [{
    title: i18n.global.t("message.News.info.b"),
    disabled: false,
    href: '/',
}, {
    title: i18n.global.t("message.Home.d"),
    disabled: false,
}]
const Rshare = ref<ShareItem<any>>();
let timerId = 0;
const router = useRouter();
const user = useUser();
const PesonURL = '/address/';
const BrowserURL = '/entity/';
const tokens = useTokens()
const onboarding = ref(0)
const activity = useActivity();
const dataAry = ref<any[]>([]);
const windowList = ref<any[]>([])
const totalPage = ref(true);
const userInfo = ref<any>({});
const pages = ref({
    current: 1,
    size: 10,
})
const backTo = (e: any) => {
    console.log(e);
    router.push(e.href)
}

Bus.on(CONN_BIG_AMOUNT, (val: any) => {
    insterData(val);
});
watch(
    () => user.info,
    async (val:any) => {
        if (val) {
            console.log('监听登录！！！！',val)
            await initShare();
            await initData();
        }
    }
);
onMounted(async () => {
    timerId = window.setInterval(() => {
        windowList.value.forEach((val: any) => {
            val.time = formatTimeAgo(val.timestamp);
        })
    }, 1000)

    await initShare();
    await initData();
    Bus.on(KLINE_RESET, (val: any) => {
        insterData(val);
    })
    document.getElementById('rout-page')?.addEventListener('scroll', scrollFn)
});
onUnmounted(() => {
    clearInterval(timerId)
    document.getElementById('rout-page')?.removeEventListener('scroll', scrollFn)
});
async function initShare() {
    user.getuserEnergyCount();
    const res: any = await get(URL_USER_INFO);
    if (res.code === 200) {
        userInfo.value = res.data.user
    }
}
const generateEmote = (constNum: any) => {
    let emojis = '\u{1F6A8}';
    let result = '';
    if (!constNum) return ''
    // 一亿 6 七千五百万 5 五千万 4 两千五百万 3 一千万2
    if (constNum >= 100000000) {
        result = emojis.repeat(6);
    }
    else if (constNum >= 75000000) {
        result = emojis.repeat(5);
    }
    else if (constNum >= 50000000) {
        result = emojis.repeat(4);
    }
    else if (constNum >= 25000000) {
        result = emojis.repeat(3);
    }
    else if (constNum >= 10000000) {
        result = emojis.repeat(2);
    } else if (constNum < 10000000) {
        result = emojis.repeat(1);
    }
    return result
}
function warpData(ary: any[]) {
    return ary.map(val => {
        // let description = ''
        let text_action = ''
        let obj = {
            title: val?.type == "swap" ?
                i18n.global.t('message.Monitor.type.a') :
                i18n.global.t('message.Monitor.type.b'),
            swap: val.type == "swap",
            inimg: getImg(val.inSymbol),
            outimg: getImg(val.outSymbol),
            inAmount: val.inAmount ? formatBigNumber(Math.abs(val.inAmount)) : 0,
            outAmount: val.outAmount ? formatBigNumber(Math.abs(val.outAmount)) : 0,
            inSymbol: val.inSymbol,
            outSymbol: val.outSymbol,
            address: val.fromTag || val.address,
            toAddress: val.toTag || val.toAddress,
            time: formatTimeAgo(val.timestamp),
            timestamp: val.timestamp,
            inusdt: formatBigNumber(val.inusdt),
            outusdt: formatBigNumber(val.outusdt),
            origin: val,
            id: uuidCreate(),
            network: Platform.TWITTER,
            hashtags: shareTags,
            shareURl: location.origin.concat(`/txn/${val.transactionHash}`),
            description: '',
        }
        if (userInfo.value?.recommendCode) {
            obj.shareURl = location.origin.concat(`/txn/${val.transactionHash}#${userInfo.value?.recommendCode}`)
        }
        if (val.type == 'swap') {
            text_action = `${generateEmote(val.outusdt)} ${numberWithCommas(Math.abs(val.outAmount))} #${val.outSymbol || ''} ($${numberWithCommas(val.outusdt)}) ${intercept(val.address || val.fromAddress || val.fromTag)} Swap to ${val.inSymbol ? `#${val.inSymbol}` : ''} ${val.inAmount != 0 ? numberWithCommas(Math.abs(val.inAmount)) : ''} ${intercept(val.toAddress || val.toTag)}  \n`
        }
        else if (val.action == 'transfer') {
            text_action = `${generateEmote(val.outusdt)} ${numberWithCommas(Math.abs(val.outAmount))} #${val.outSymbol || ''} ($${numberWithCommas(val.outusdt)}) ${intercept(val.address || val.fromAddress || val.fromTag)} Send to ${val.inSymbol ? `#${val.inSymbol}` : ''} ${val.inAmount != 0 ? numberWithCommas(Math.abs(val.inAmount)) : ''} ${intercept(val.toAddress || val.toTag)} \n`
        }
        else if (val.action == 'deposit') {
            text_action = `${generateEmote(val.outusdt)} ${numberWithCommas(Math.abs(val.outAmount))} #${val.outSymbol || ''} ($${numberWithCommas(val.outusdt)}) ${intercept(val.address || val.fromAddress || val.fromTag)} ${val.action} to ${val.inSymbol ? `#${val.inSymbol}` : ''} ${val.inAmount != 0 ? numberWithCommas(Math.abs(val.inAmount)) : ''} ${intercept(val.toAddress || val.toTag)} \n`
        }
        else {
            text_action = `${generateEmote(val.outusdt)} ${numberWithCommas(Math.abs(val.outAmount))} #${val.outSymbol || ''} ($${numberWithCommas(val.outusdt)}) ${intercept(val.address || val.fromAddress || val.fromTag)} ${val.action} from ${val.inSymbol ? `#${val.inSymbol}` : ''} ${val.inAmount != 0 ? numberWithCommas(Math.abs(val.inAmount)) : ''} ${intercept(val.toAddress || val.toTag)} \n`
        }
        obj.description = text_action
        return obj
    });
}

/**过滤地址和交易所名称 */
function intercept(char: string, num = 6) {
    // console.log('过滤地址!!!', char)
    if (!char) return;
    if (!char.startsWith('0x')) return char
    const seat = "***";
    const seat_ = "...";
    let char_ = char;
    if (!char) return;
    if (char_.length < num) return char_;
    char_ = char.slice(0, num).concat(seat).concat(char.slice(-num));
    if (char.indexOf("0x") === -1) {
        char_ = char;
        if (char.length > 20) {
            char_ = char.slice(0, 20).concat(seat_);
        }
    }
    return char_;
}
//下滑事件
function scrollFn() {
    const element = document.getElementById('rout-page');
    if (element!.scrollTop + element!.clientHeight >= element!.scrollHeight) {
        // console.log('触底加载!!!!!!!!!')
        if (totalPage) {
            pages.value.current++;
            initData()
        }
    }
}
function toToekn(id: string) {
    window.open("/token/" + id)
}
function getImg(address: string) {
    return tokens.getImg(address);
}
function insterData(val: any) {
    if (!val) return
    let t = warpData([val]);
    // t.push(...dataAry.value);
    t.sort((a: any, b: any) => a.timestamp > b.timestamp ? -1 : 1);
    let list = t.slice(0, 10);
    windowList.value = [...list, ...windowList.value]
}
async function initData() {
    let res: any = await get(URL_KLINE_HISTORY, { group: "BIG_AMOUNT", size: pages.value.size, current: pages.value.current });
    // console.log('链上活动初始化#########################', res)
    let list: any = []
    if (res.data.length < pages.value.size) {
        totalPage.value = false
    }
    if (res.data.length != 0) {
        list = warpData(res.data)
        dataAry.value = [...dataAry.value, ...list];
        windowList.value = dataAry.value
    }
    console.warn('链上活动#########################', windowList.value)
}
const findKey = (targetValue: any, item: any) => {
    let key = ''
    for (let i in item) {
        if (targetValue == item[i]) {
            key = i
        }
    }
    return key
}
function naviGetTo(event: any, str: any) {
    const key = findKey(str, event)
    console.log('点击跳转', key, str, event)
    // return
    if (key == 'address') {
        if (event.fromAddressType == 'eoa' && event.address) {
            window.open(PesonURL + event.address)
        }
    }
    if (key == 'toTag') {
        if (event.toEntityId && (event.toAddressType == 'cex' || event.toAddressType == 'fund')) {
            window.open(BrowserURL + event.toEntityId)
        }
    }
    if (key == 'fromTag') {
        if (event.fromEntityId && (event.fromAddressType == 'cex' || event.fromAddressType == 'fund')) {
            window.open(BrowserURL + event.fromEntityId)
        }
    }
    if (key == 'toAddress') {
        if (event.toAddressType == 'eoa') {
            window.open(PesonURL + event.toAddress)
        }
    }
    if (key == 'toEntityId') {
        if (event.toAddressType == 'fund' || event.toAddressType == 'cex') {
            window.open(BrowserURL + event.toEntityId)
        }
    }
    if (key == 'fromEntityId') {
        if (event.fromAddressType == 'fund' || event.fromAddressType == 'cex') {
            window.open(BrowserURL + event.fromEntityId)
        }
    }
}



const changeWindowList = (list: any) => {
    // let result = []
    // for (let i = 0; i < list.length; i += 2) {
    //     if (i + 1 < list.length) {
    //         result.push([list[i], list[i + 1]]);
    //     } else {
    //         result.push([list[i]]);
    //     }
    // }
    windowList.value = list
    console.warn('链上活动#########################', windowList.value)
}

</script>

<style lang="less" scoped>
@import url("./index.less");
</style>